package com.polarbookshop.catalogservice.service

import com.polarbookshop.catalogservice.domain.Book
import com.polarbookshop.catalogservice.domain.BookAlreadyExistsException
import com.polarbookshop.catalogservice.domain.BookNotFoundException
import com.polarbookshop.catalogservice.domain.BookRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class BookService {

    @Autowired
    private lateinit var bookRepository: BookRepository;

    fun viewBookList(): Iterable<Book> {
        return bookRepository.findAll()
    }

    fun viewBookDetails(isbn: String): Book {
        return bookRepository.findByIsbn(isbn) ?: throw BookNotFoundException(isbn)
    }

    fun addBookToCatalog(book: Book): Book {
        if (bookRepository.existsByIsbn(book.isbn)) {
            throw BookAlreadyExistsException(book.isbn)
        }
        return bookRepository.save(book)
    }

    fun removeBookFromCatalog(isbn: String) {
        bookRepository.deleteByIsbn(isbn)
    }

    fun editBookDetails(isbn: String, book: Book): Book {
        return bookRepository.findByIsbn(isbn)?.let {
            val bookToUpdate = Book(
                it.id,
                it.isbn,
                book.title,
                book.author,
                book.price,
                book.publisher,
                it.createdDate,
                it.lastModifiedDate,
                it.createdBy,
                it.lastModifiedBy,
                it.version
            )
            return bookRepository.save(bookToUpdate)
        } ?: addBookToCatalog(book)
    }
}